/**
 * Created by way on 16/9/17.
 */

const $ = require('../lib/kdom');
import cfg from '../config';
import {get, getView} from '../util/api';

// let _view = require('raw-loader!./list.html'); // eslint-disable-line
let _view = '';

/* global liBid */
/* global ulList */


let _user = {};
let _us = [];
/*
let _us = [['500', '15161584615', '夏天', '77732656'], ['400', '18011111111', '白应梅', '77732656'],
 ['350', '15816354851', '柏仁燕', '77732656'], ['300', '13513154899', '包颜琳', '77732656'],
 ['280', '18286479136', '鲍学梅', '77732656'], ['260', '18024631478', '鲍  颖', '77732656'],
 ['220', '18631549875', '蔡玲芳', '77732656'], ['200', '18312345678', '蔡  艳', '77732656'],
 ['212', '15800000000', '蔡  玉', '77732656'], ['200', '13712365487', '曹发敏', '77732656']];
*/

export default class {
  path = '/bid/list$';
  hash = '/bid/list';
  title = '拍卖';

  constructor(opt) {
    opt = opt || {};
    this.path = opt.path || this.path;
    this.hash = opt.hash || this.hash;
    this.title = opt.title || this.title;
  }

  // 输出视图
  view(cb) {
    if (!_view) {
      // 静态资源浏览器有缓存,增加时标,强制刷新!
      getView(`${cfg.bid.view.host}${cfg.bid.view.list}?t=${(+new Date())}`, '', (rs) => {
        _view = rs;
        cb(null, _view);
      });
    } else
      cb(null, _view);
  }

  // 在已经加载的视图上操作
  bind(dv, params) {
    _user = params || {};
    // alert(JSON.stringify(_user));
    list();
  }
}

function list() {
/*
  if (_us && _us.length > 0) {
    render(_us);
  } else
*/
  get(`${cfg.bid.api.host}${cfg.bid.api.list}`, `bidStatus=2&pid=${_user.pid}`, (rs) => {
    // alert(`getUsers rs:${rs}`);
    if (rs) {
      const r = JSON.parse(rs);
      if (r.rc === 200 && r.getBidUser && r.getBidUser.length > 0) {
        try {
          if (_us.toString() !== r.getBidUser.toString()) {
            _us = r.getBidUser;
            render(_us);
          }
        } catch (e) {
          alert(e.message);
        }
      } else
        alert('获取数据失败，请在WIFI网络下重试!');
    }
    // 5 秒刷新一次
    setTimeout(list, 5000);
  });
}

//  label
function render(us) {
  ulList.innerHTML = '';
  us.forEach((r, idx) => {
    if (Number(r[0]) > 0) {
      const val = idx == 0 ? `${r[2]}(${r[1]})` : `${r[2]}(${r[1].substr(7)})`;
      const li = $.dc(null, 'li');
      $.html(li, `<li><div class="item-content"><div class="item-inner">
<div class="item-title">${idx + 1}、${val}</div>
<div class="item-after">￥${r[0]}</div></div></div></li>`);
      ulList.appendChild(li); // liBid.parentNode
    }
  });
}
